// pages/profile/profile.js
import api from "../../utils/api";
import { myRequest } from "../../utils/request";
import Notify from "@vant/weapp/notify/notify";
import Cache from "../../utils/cache";
import Tool from "../../utils/tool";
import Dialog from '@vant/weapp/dialog/dialog';


Page({

    /**
     * 页面的初始数据
     */
    data: {
        isLogin: false,
        userInfo: {
            username: "还未登录，请先登录！",
            headPic: api.getImageUrl("common/mine_normal.jpg")
        },
        basePhotoUrl: api.BASE_URL + "/photo/view?filename=",
        editUser: {},
        profileDialogVisible: false,
        // 实名认证状态
        verificationStatus: {
            isVerified: false,
            verifyDate: null
        },
        // 会员状态
        memberStatus: {
            isVip: false,
            expireDate: null,
            memberType: 'normal'
        },
        onBeforeClose: (action, done) => {
            if(action === "confirm") {
              return false;
            } else {
              wx.showTabBar({
                animation: true
              });
              return true;
            }
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
       this.validateLoginState();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 每次显示页面时检查登录状态（validateLoginState内部会调用checkUserStatus）
        this.validateLoginState();

        // 检查是否是从社交页面跳转过来的
        if (getApp().globalData.fromSocialPage && !this.data.isLogin) {
            // 如果是从社交页面跳转过来的，且未登录，才显示登录提示
            setTimeout(() => {
                this.showLoginConfirm();
                // 重置标记
                getApp().globalData.fromSocialPage = false;
            }, 500);
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        this.validateLoginState();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

    // 预览图片
    previewHead: function () {
        let userInfo = this.data.userInfo;
        let basePhotoUrl = this.data.basePhotoUrl;
        wx.previewImage({
             current: userInfo.headPic === userInfo.wxHeadPic ? userInfo.wxHeadPic : basePhotoUrl + userInfo.headPic,
             urls: [userInfo.headPic === userInfo.wxHeadPic ? userInfo.wxHeadPic : basePhotoUrl + userInfo.headPic]
        })
    },
    // 验证登录状态
    validateLoginState: async function() {
        wx.showLoading({
            title: "获取登录信息...",
            mask: true
        })
        const loginToken = Cache.getCache(getApp().globalData.SESSION_KEY_LOGIN_USER);
        const userInfo = Cache.getCache(getApp().globalData.SESSION_KEY_USER_INFO);
        
        if(Tool.isEmpty(loginToken) || Tool.isEmpty(userInfo)) {
            wx.hideLoading();
            this.setData({
                isLogin: false,
                userInfo: {
                    username: "还未登录，请先登录！",
                    headPic: api.getImageUrl("common/mine_normal.jpg")
                }
            });
            return;
        }
        
        try {
            // 解析用户信息
            const parsedUserInfo = JSON.parse(userInfo);

            // 存储userId到本地存储并在控制台打印
            const userId = parsedUserInfo.id;
            if (userId) {
                wx.setStorageSync('userId', userId);
                console.log('=== 登录状态验证 ===');
                console.log('用户ID已存储:', userId);
                console.log('用户信息:', parsedUserInfo);
                console.log('==================');
            } else {
                console.warn('用户信息中没有找到ID字段');
            }

            this.setData({
                userInfo: parsedUserInfo,
                isLogin: true,
                editUser: parsedUserInfo
            });

            // 检查用户状态（实名认证和会员状态）
            this.checkUserStatus();
        } catch (error) {
            console.error("获取登录信息失败", error);
            this.setData({
                isLogin: false,
                userInfo: {
                    username: "还未登录，请先登录！",
                    headPic: api.getImageUrl("common/mine_normal.jpg")
                }
            });
        }
        wx.hideLoading();
    },
    
    // 登录操作
    getLoginUser: function() {
        wx.showLoading({
            title: "正在登录...",
            mask: true
        })
        wx.getUserProfile({
            desc: "获取用户相关信息",
            success: res => {
                if(res.errMsg === "getUserProfile:ok") {
                    let username = res.userInfo.nickName;
                    let headPic = res.userInfo.avatarUrl;
                    wx.login({
                        success: async res => {
                            if (res.errMsg === "login:ok") {
                                try {
                                    console.log("开始登录请求，code:", res.code);
                                    // 调用后端接口，验证用户数据
                                    const response = await api.wxLogin(res.code, headPic, username);
                                    console.log("登录请求成功:", response);
                                    if(response.data.code === 0) {
                                        Notify({ type: "success", message: response.data.msg, duration: 1000 });
                                        // 存储token和用户信息到缓存
                                        Cache.setCache(getApp().globalData.SESSION_KEY_LOGIN_USER, response.data.data.token, 3600);
                                        Cache.setCache(getApp().globalData.SESSION_KEY_USER_INFO, JSON.stringify(response.data.data), 3600);

                                        // 存储userId到本地存储并在控制台打印
                                        const userId = response.data.data.id;
                                        if (userId) {
                                            wx.setStorageSync('userId', userId);
                                            console.log('=== 微信登录成功 ===');
                                            console.log('用户ID已存储:', userId);
                                            console.log('完整用户信息:', response.data.data);
                                            console.log('Token:', response.data.data.token);
                                            console.log('==================');
                                        } else {
                                            console.warn('登录响应中没有找到用户ID');
                                        }

                                        this.setData({
                                            userInfo: response.data.data,
                                            editUser: response.data.data,
                                            isLogin: true
                                        });

                                        // 登录成功后立即检查用户状态
                                        this.checkUserStatus();
                                    } else {
                                        console.error("登录失败，错误码:", response.data.code, "错误信息:", response.data.msg);
                                        Notify({ type: "danger", message: response.data.msg || "登录失败", duration: 2000 });
                                    }
                                } catch (error) {
                                    console.error("登录请求异常:", error);
                                    Notify({ 
                                        type: "danger", 
                                        message: error.errMsg || "网络请求失败，请稍后再试", 
                                        duration: 2000 
                                    });
                                }
                            } else {
                                console.error("微信登录失败:", res.errMsg);
                                Notify({ 
                                    type: "danger", 
                                    message: "微信登录失败", 
                                    duration: 2000 
                                });
                            }
                            wx.hideLoading();
                        },
                        fail: res => {
                            console.error("wx.login API调用失败:", res);
                            Notify({ 
                                type: "danger", 
                                message: "登录失败，请检查网络", 
                                duration: 2000 
                            });
                            wx.hideLoading();
                        }
                    })
                } else {
                    console.error("获取用户信息失败:", res.errMsg);
                    Notify({ 
                        type: "danger", 
                        message: "获取用户信息失败", 
                        duration: 2000 
                    });
                    wx.hideLoading();
                }
            },
            fail: res => {
                console.error("getUserProfile API调用失败:", res);
                Notify({ 
                    type: "danger", 
                    message: "获取用户信息失败", 
                    duration: 2000 
                });
                wx.hideLoading();
            }
        })
    },
    // 跳转我的订单页面
    goToOrderList: function() {
        if(this.authUser()) {
            return;
        }
        wx.navigateTo({
            url: "/package/pages/myOrder/myOrder?userId=" + this.data.editUser.id
        })
    },
    // 跳转我的评价页面
    goToCommentList: function() {
        if(this.authUser()) {
            return;
        }
        wx.navigateTo({
            url: "/package/pages/myComment/myComment?userId=" + this.data.editUser.id
        })
    },
    
    // 跳转到我的相册页面
    goToAlbum: function() {
        if(this.authUser()) {
            return;
        }
        wx.navigateTo({
            url: "/pages/album/album?userId=" + this.data.editUser.id
        })
    },

    // 跳转到实名认证页面
    goToVerify: function() {
        if(this.authUser()) {
            return;
        }
        wx.navigateTo({
            url: "/pages/verify/verify"
        })
    },
    // 展示个人信息的模态框
    showProfileDialog: function() {
        wx.hideTabBar({
            animation: true
        });
        this.setData({profileDialogVisible: true});
    },
    // 关闭个人信息的模态框
    closeProfileDialog: function() {
        wx.showTabBar({
            animation: true
        });
        this.setData({profileDialogVisible: false});
    },
    // 验证用户是否登录
    authUser: function() {
        if (!this.data.isLogin) {
            this.showLoginConfirm();
            return true;
        }
        return false;
    },
    
    // 显示登录确认对话框
    showLoginConfirm: function() {
        Dialog.confirm({
            title: '提示',
            message: '该功能需要登录后才能使用，是否立即登录？',
        }).then(() => {
            this.getLoginUser();
        }).catch(() => {
            // 用户取消登录
        });
    },
    
    // 退出登录
    logout: async function() {
        const loginUser = Cache.getCache(getApp().globalData.SESSION_KEY_LOGIN_USER);
        try {
            const res = await api.logout(loginUser);
            if(res.data.code === 0) {
                Notify({ type: "success", message: res.data.msg, duration: 1000 });
            }
            // 清除所有用户相关缓存
            Cache.removeCache(getApp().globalData.SESSION_KEY_LOGIN_USER);    
            Cache.removeCache(getApp().globalData.SESSION_KEY_USER_INFO);
            
            // 清除userId
            wx.removeStorageSync('userId');
            console.log('用户已退出登录，userId已清除');
            
            this.setData({isLogin: false, userInfo: {
                username: "还未登录，请先登录！",
                headPic: api.getImageUrl("common/mine_normal.jpg")
            }});
        } catch (error) {
            console.error('退出登录失败', error);
            Notify({ type: "danger", message: "退出登录失败", duration: 2000 });
        }
    },
    // 打开上传图片的窗口
    openUploadCoverPhoto: function() {
        wx.chooseMedia({
            count: 1,
            mediaType: ["image"],
            sourceType: ["album"],
            success: (res) => {
                let file = res.tempFiles[0].tempFilePath;
                // 获取文件后缀
                const fileFormat = file.substring(file.lastIndexOf(".") + 1, file.length);
                const fileManager = wx.getFileSystemManager();
                const base64 = fileManager.readFileSync(file, "base64");
                this.uploadCoverPhoto(`data:image/${fileFormat};base64,${base64}`);
            },
            fail: (res) => {
                wx.showToast({
                    title: "上传失败",
                    icon: "error"
                })
            }
        })
    },
    // 图片上传操作
    async uploadCoverPhoto(base64) {
        try {
            const res = await api.uploadPhoto(base64);
            if(res.data.code === 0) {
                wx.showToast({
                    title: "上传成功！",
                    icon: "success"
                })
                this.setData({
                    ["editUser.headPic"]: res.data.data
                })
            } else {
                wx.showToast({
                    title: res.data.msg,
                    icon: "none"
                })
            }
        } catch (error) {
            console.error('上传图片失败', error);
            wx.showToast({
                title: "上传失败",
                icon: "error"
            })
        }
    },
    // 模态框内容发生变化
    onChangeDialog: function(e) {
        let type = e.target.dataset.type;
        this.setData({
            editUser: {
                ...this.data.editUser,
                [type]: e.detail 
            }
        })
    },
    // 更新个人信息
    updateUserInfo: async function() {
        try {
            const userData = {
                ...this.data.editUser,
                token: Cache.getCache(getApp().globalData.SESSION_KEY_LOGIN_USER)
            };
            const res = await api.updateUserInfo(userData);
            if(res.data.code === 0) {
                Notify({ type: "success", message: res.data.msg, duration: 1000 });
                this.validateLoginState();
                this.closeProfileDialog();
            } else {
                Notify({ type: "danger", message: res.data.msg, duration: 2000 });
            }
        } catch (error) {
            console.error('更新个人信息失败', error);
            Notify({ type: "danger", message: "更新个人信息失败", duration: 2000 });
        }
    },

    // 点击实名认证卡片
    onVerificationTap: function() {
        if (!this.data.isLogin) {
            this.showLoginConfirm();
            return;
        }

        if (this.data.verificationStatus.isVerified) {
            wx.showToast({
                title: '您已完成实名认证',
                icon: 'success',
                duration: 2000
            });
        } else {
            // 跳转到实名认证页面
            this.goToVerify();
        }
    },

    // 点击会员状态卡片
    onMemberTap: function() {
        if (!this.data.isLogin) {
            this.showLoginConfirm();
            return;
        }

        if (this.data.memberStatus.isVip) {
            wx.showModal({
                title: '会员信息',
                content: `您是VIP会员\n到期时间：${this.data.memberStatus.expireDate || '永久'}`,
                showCancel: false,
                confirmText: '知道了'
            });
        } else {
            wx.showModal({
                title: '开通会员',
                content: '开通VIP会员享受更多特权功能',
                confirmText: '立即开通',
                cancelText: '暂不开通',
                success: (res) => {
                    if (res.confirm) {
                        // 跳转到会员开通页面
                        wx.showToast({
                            title: '功能开发中...',
                            icon: 'none',
                            duration: 2000
                        });
                    }
                }
            });
        }
    },

    // 检查用户状态（实名认证和会员状态）
    checkUserStatus: async function() {
        if (!this.data.isLogin) {
            console.log('用户未登录，跳过状态检查');
            return;
        }

        try {
            // 优先从本地存储获取userId，其次从缓存的用户信息获取
            let userId = wx.getStorageSync('userId');
            if (!userId) {
                const userInfo = Cache.getCache(getApp().globalData.SESSION_KEY_USER_INFO);
                if (userInfo) {
                    const parsedUserInfo = JSON.parse(userInfo);
                    userId = parsedUserInfo.id;
                    if (userId) {
                        wx.setStorageSync('userId', userId);
                    }
                }
            }

            console.log('=== 开始检查用户状态 ===');
            console.log('当前用户ID:', userId);
            console.log('登录状态:', this.data.isLogin);

            if (!userId) {
                console.error('无法获取用户ID，跳过状态检查');
                return;
            }

            // 检查实名认证状态
            console.log('正在检查实名认证状态...');
            const verifyRes = await api.checkVerificationStatus(userId);
            console.log('实名认证状态API响应:', verifyRes);

            if (verifyRes.data && verifyRes.data.code === 200) {
                const verifyData = verifyRes.data.data;
                const newVerificationStatus = {
                    isVerified: verifyData.isVerified || false,
                    verifyDate: verifyData.verifyDate || null,
                    message: verifyData.message || '未知状态'
                };

                this.setData({
                    verificationStatus: newVerificationStatus
                });

                console.log('✅ 实名认证状态更新成功:', newVerificationStatus);
                console.log('认证状态:', verifyData.isVerified ? '已认证' : '未认证');
                if (verifyData.realName) {
                    console.log('认证姓名:', verifyData.realName);
                }
                if (verifyData.idCard) {
                    console.log('身份证号:', verifyData.idCard);
                }
            } else {
                console.error('❌ 检查实名认证状态失败:', verifyRes.data ? verifyRes.data.message : '未知错误');
            }

            // 检查会员状态
            console.log('正在检查会员状态...');
            const memberRes = await api.checkMemberStatus();
            console.log('会员状态API响应:', memberRes);

            if (memberRes.data && memberRes.data.code === 200) {
                const memberData = memberRes.data.data;
                const newMemberStatus = {
                    isVip: memberData.isVip || false,
                    expireDate: memberData.expireDate || null,
                    memberType: memberData.memberType || 'normal'
                };

                this.setData({
                    memberStatus: newMemberStatus
                });

                console.log('✅ 会员状态更新成功:', newMemberStatus);
            } else {
                console.error('❌ 检查会员状态失败:', memberRes.data ? memberRes.data.message : '未知错误');
            }

            console.log('=== 用户状态检查完成 ===');
        } catch (error) {
            console.error('❌ 检查用户状态异常:', error);
        }
    }
})